const path = require('path');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.(le|c)ss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'less-loader',
        ],
      },
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
    ],
  },
  performance: {
    hints: false,
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: { // 分包
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: 10,
          enforce: true,
        },
        elementUI: {
          test: /[\\/]node_modules[\\/]element-ui[\\/]/,
          name: 'ele-ui',
          priority: 20,
          enforce: true,
        },
        yh: {
          test: /[\\/]node_modules[\\/]yh-ui-components[\\/]/,
          name: 'yh',
          priority: 25,
          enforce: true,
        },
        commons: {
          name: 'commons',
          test: path.resolve(__dirname, 'src/components'),
          minChunks: 2,
          priority: 5,
          reuseExistingChunk: true,
        },
      },
    },
    runtimeChunk: {
      name: 'manifest', // 配置主文件别名
    },
    moduleIds: 'deterministic', // hash化模块名称
    minimizer: [ // 压缩js、css
      new TerserPlugin({
        parallel: true,
      }),
      new OptimizeCSSAssetsPlugin(),
    ],
  },
  plugins: [
    new CleanWebpackPlugin(), // 自动清除打包文件夹
    new webpack.DefinePlugin({ // 定义环境
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    // 配置index.html
    new HtmlWebpackPlugin({
      title: 'vue-app-base',
      template: path.resolve(__dirname, 'public/index.html'),
      favicon: path.resolve(__dirname, 'public/favicon.ico'),
      minify: {
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        removeComments: true,
        removeAttributeQuotes: true,
      },
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:8].css',
      chunkFilename: 'css/[id].[contenthash:8].css',
    }),
    new webpack.ids.HashedModuleIdsPlugin(),
  ],
});
